<?php

define('ROOT_PATH', realpath(__DIR__ . '/../')); // 系统根目录
define('CORE_PATH', ROOT_PATH . '/Core'); // 框架基础类库目录
define('LIBS_PATH', ROOT_PATH . '/Libs'); // 用户类库目录
define('APP_PATH', ROOT_PATH . '/App'); // 应用模块目录
define('DATA_PATH', ROOT_PATH . '/Data'); // 数据存储目录
define('PUBLIC_PATH', ROOT_PATH . '/Public'); // 网站访问根目录
define('UPLOAD_PATH', ROOT_PATH . '/Public/uploads/'); // 上传文件存储目录
define('UPLOAD_URL', '/uploads/'); // 上传文件访问网址

require CORE_PATH . '/Application.php'; // 引入框架 
$app = new Application();
$app->run(false); // 只引入系统框架，不执行控制器

$worker = new Daemon('baidu', 'www', 'www', DATA_PATH . '/Daemon');

$worker->setTask(10, function () {

    if (cache('baidu', 'delay')) {
        return;
    }

    $ids = Cms()->Article()->getUnpushedIds();

    if (!$ids) {
        wlog('没有新的推送内容', 'baidu');
        return;
    }

    foreach ($ids as $id) {
        $urls[$id] = \Sys('site_root') . "/article/page/id/{$id}";
    }

    $api = 'http://data.zz.baidu.com/urls?site=' . \Sys('site_root') . '&token=' . \Sys('baidu_token');
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $api,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );

    curl_setopt_array($ch, $options);

    $resp = curl_exec($ch);

    wlog($resp, 'baidu');

    $result = json_decode($resp, true);

    $pushed_ids = [];

    if ($result['success']) {
        if ($result['success'] == count($ids)) {
            $pushed_ids = $ids;
        } else {
            foreach ($urls as $id => $url) {
                if (!in_array($url, $result['not_same_site']) && !in_array($url, $result['not_valid'])) {
                    $pushed_ids[] = $id;
                }
            }
        }
    } else {
        if ($result['message'] == 'over quota') {
            if (!cache('baidu', 'delay', 1, 300)) {
                wlog('设置延迟失败', 'baidu');
            }
        }
    }

    if ($pushed_ids) {
        $result = Cms()->Article()->setPushed($pushed_ids);
        if (!$result) {
            wlog('设置已推送失败', 'baidu');
        }
    }
});

$worker->run();

